import 'package:flutter/services.dart';
import 'package:flutter_project/common/route_page/route_name.dart';
import 'package:flutter_project/user/user_login/user_login_view.dart';
import 'package:mobile_number/mobile_number.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../../config/theme_color.dart';
import '../../common/privacy/dialog_common_view.dart';
import '../../common/utils/screen_size_utils.dart';
import '../../config/app_bar_view.dart';
import '../../generated/l10n.dart';
import 'agree_privacy_login_view.dart';

class UserLoginPhoneView extends StatefulWidget {
  const UserLoginPhoneView({super.key});

  @override
  State<UserLoginPhoneView> createState() => _UserLoginViewState();
}

class _UserLoginViewState extends State<UserLoginPhoneView> {
  double textSize = 12.0;
  final ValueNotifier<bool> isChose = ValueNotifier<bool>(false);
  final ValueNotifier<String> mobileNumber = ValueNotifier<String>('');
  List<SimCard> _simCard = <SimCard>[];

  @override
  Widget build(BuildContext context) {
    return CommonAppWidget.navAppBar(
      bgColor: Colors.white,
      childWidget: SizedBox(
        width: ScreenSizeUtils.deviceScreenHeight(context),
        child: Container(
          color: Colors.white,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(
                  height: 50,
                ),
                Image.asset(
                  'assets/images/ic_launcher.png',
                  width: 70,
                ),
                const SizedBox(
                  height: 20,
                ),
                Text(
                  S.of(context).appTitle,
                  style: const TextStyle(
                      fontSize: 15, fontWeight: FontWeight.w500),
                ),
                const SizedBox(
                  height: 80,
                ),
                ValueListenableBuilder(
                    valueListenable: mobileNumber,
                    builder:
                        (BuildContext context, String value, Widget? child) {
                      return Text(
                        getRightPhone(value),
                        style: const TextStyle(
                            fontSize: 24, fontWeight: FontWeight.bold),
                      );
                    }),
                const SizedBox(
                  height: 40,
                ),
                GestureDetector(
                  onTap: () {
                    if (isChose.value == false) {
                      ConfirmAlertDialog.showPrivacyDialog(context,
                          childWidget: const AgreePrivacyLoginView());
                    }
                  },
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 35),
                    alignment: Alignment.center,
                    height: 45,
                    decoration: BoxDecoration(
                        color: const Color(0xff6f66d6),
                        gradient: LinearGradient(colors: [
                          const Color(0xFFD175FE),
                          ThemeColor.mainColor
                        ]),
                        borderRadius: BorderRadius.circular(25)),
                    child: const Text(
                      '本机号码一键登录',
                      style: TextStyle(
                          fontSize: 14,
                          color: Colors.white,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ValueListenableBuilder(
                        valueListenable: isChose,
                        builder:
                            (BuildContext context, bool value, Widget? child) {
                          String iconStr = value == false
                              ? 'assets/images/ic_agree_uncheck.png'
                              : 'assets/images/ic_agree_check.png';
                          return GestureDetector(
                            onTap: () {
                              isChose.value = !isChose.value;
                            },
                            child: Image.asset(
                              iconStr,
                              width: 18,
                            ),
                          );
                        }),
                    const SizedBox(
                      width: 4,
                    ),
                    RichText(
                        text: TextSpan(
                            text: '我已阅读并同意',
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                isChose.value = !isChose.value;
                              },
                            style: TextStyle(
                                color: ThemeColor.textColorSecond,
                                fontSize: textSize),
                            children: [
                          TextSpan(
                            text: "《用户协议》",
                            style: TextStyle(
                                color: const Color(0xFF7F69D9),
                                fontSize: textSize),
                            recognizer: TapGestureRecognizer()..onTap = () {},
                          ),
                          TextSpan(
                            text: '和',
                            style: TextStyle(
                                color: ThemeColor.textColorSecond,
                                fontSize: textSize),
                          ),
                          TextSpan(
                            text: "《隐私声明》",
                            style: TextStyle(
                                color: const Color(0xFF7F69D9),
                                fontSize: textSize),
                            recognizer: TapGestureRecognizer()..onTap = () {},
                          )
                        ]))
                  ],
                ),
                const SizedBox(
                  height: 100,
                ),
                GestureDetector(
                  onTap: () {
                    RouteNames.push(const UserLoginView());
                  },
                  child: Container(
                    color: Colors.white,
                    child: Column(
                      children: [
                        Container(
                          width: 50,
                          height: 50,
                          decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: ThemeColor.sendMsgColor,
                                width: 1.0,
                              )),
                          child: Icon(
                            Icons.phone_android_rounded,
                            size: 20,
                            color: ThemeColor.textColorSecond,
                          ),
                        ),
                        const SizedBox(
                          height: 4,
                        ),
                        Text(
                          '账号密码登录',
                          style: TextStyle(
                              color: ThemeColor.textColorSecond, fontSize: 14),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    MobileNumber.listenPhonePermission((bool isPermissionGranted){
      if(isPermissionGranted){
        initMobileNumberState();
      }else{

      }
    });
    initMobileNumberState();
  }

  void requestPermission() async {
    if (!await MobileNumber.hasPhonePermission) {
      await MobileNumber.requestPhonePermission;
    }
  }

  Future<String?> initMobileNumberState() async {
    requestPermission();
    try {
      mobileNumber.value = await MobileNumber.mobileNumber ?? '';
      _simCard = await MobileNumber.getSimCards ?? [];
      return mobileNumber.value;
    } on PlatformException catch (e) {
      debugPrint("Failed to get mobile number because of '${e.message}'");
    }
    return '';
  }

  String getRightPhone(String mobile) {
    String newStr = '';
    if (mobile.isNotEmpty && mobile.length > 11) {
      newStr = mobile.substring(mobile.length - 11);
      if (newStr.length > 10) {
        newStr = newStr.replaceRange(3, 7, '****');
      }
    }
    return newStr;
  }
}
